<script setup lang="ts">
import {
  PermissionVO,
  updatePermission,
  UpdatePermissionParams
} from "@/api/modules/system";
import { message } from "@/utils/message";
import { cloneDeep } from "@pureadmin/utils";
import { PlusColumn, PlusDrawerForm } from "plus-pro-components";
import { ref, watch } from "vue";

defineOptions({
  name: "permission-edit-from"
});

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  row: {
    type: Object as PropType<PermissionVO>,
    default: () => ({})
  }
});

const emit = defineEmits(["update:visible", "refresh"]);
const visible = ref(props.visible);

const columns: PlusColumn[] = [
  {
    label: "权限名",
    width: 120,
    prop: "name"
  },
  {
    label: "权限编码",
    width: 120,
    prop: "code"
  },
  {
    label: "权限类型",
    width: 120,
    prop: "type",
    valueType: "select",
    options: [
      {
        label: "目录",
        value: 1
      },
      {
        label: "权限",
        value: 2
      }
    ]
  },
  {
    label: "状态",
    width: 120,
    prop: "status",
    valueType: "select",
    options: [
      {
        label: "启用",
        value: 1
      },
      {
        label: "禁用",
        value: 0
      }
    ]
  },
  {
    label: "描述",
    prop: "description",
    valueType: "textarea"
  }
];

const state = ref<UpdatePermissionParams>({
  id: "",
  name: "",
  code: "",
  type: null,
  parentId: "",
  status: null,
  description: ""
});
const initState = cloneDeep(state.value);

const typeOptions = [
  {
    label: "目录",
    value: 1
  },
  {
    label: "权限",
    value: 2
  }
];

function handleCancel() {
  visible.value = false;
  emit("update:visible", false);
}

function handleConfirm() {
  updatePermission(state.value).then(res => {
    if (res.success) {
      emit("refresh");
      handleCancel();
      message("更新成功", { type: "success" });
    }
  });
}

watch(
  () => props.visible,
  newVal => {
    visible.value = newVal;
    // 当抽屉打开时，初始化表单数据
    if (newVal && props.row) {
      const param = props.row;
      state.value.id = param.id;
      state.value.name = param.name;
      state.value.code = param.code;
      state.value.type = param.type;
      state.value.status = param.status;
      state.value.description = param.description;
    } else {
      state.value = initState;
    }
  }
);
</script>

<template>
  <PlusDrawerForm
    v-if="visible"
    v-model:visible="visible"
    v-model="state"
    size="25%"
    :title="row.name"
    :form="{ columns, labelPosition: 'right', labelWidth: 90 }"
    @cancel="handleCancel"
    @confirm="handleConfirm"
  >
    <template #plus-field-code>
      <el-input v-model="state.code" disabled />
    </template>
    <template #plus-field-type>
      <el-select v-model="state.type" disabled>
        <el-option
          v-for="item in typeOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </template>
  </PlusDrawerForm>
</template>
